package com.hilinos.ftp;

import com.hilinos.common.common.ReturnCode;
import com.hilinos.common.common.handler.ITokenHandler;
import com.hilinos.common.common.handler.NoTokenEntity;
import com.hilinos.common.util.AssertUtils;
import com.hilinos.common.util.JwtUtils;
import com.hilinos.common.util.LicenseUtils;
import com.hilinos.ftp.anno.Auth;
import com.hilinos.ftp.pojo.UserPojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;

/**
 * @author qhl
 */
@Component
public class TokenHandler implements ITokenHandler {

    @Value("${com.hilinos.license}")
    private String license;

    @Override
    public boolean checkToken(String token, HttpServletRequest request, HandlerMethod method, NoTokenEntity noTokenEntity) {

        LicenseUtils.checkLicense(license);
        String uri = request.getRequestURI();

        if (uri.contains("/static/")) {
            return true;
        }

        UserPojo userPojo = JwtUtils.check(token, UserPojo.class);
        AssertUtils.isNotEmpty(userPojo, ReturnCode.AUTH_ERROR);
        request.setAttribute("userinfo", userPojo);
        Auth auth = method.getMethodAnnotation(Auth.class);
        if (auth == null) {
            return true;
        }
        AssertUtils.isRex(auth.value().equals(userPojo.getUsertype()), ReturnCode.AUTH_NO_OPERATOR);
        return true;
    }
}
